<?php
/**
 * 跃飞科技版权所有 @2017
 * User: 钟贵廷
 * Date: 2017/5/23
 * Time: 17:36
 */
namespace app\admin\controller;
use think\Db;
use think\Image;
use think\Loader;
use think\Request;

class Ad extends Admin
{
    public function lst($keyword = '')
    {
        $adPositionModel =  model('Ad');
        $data = $adPositionModel -> search(trim($keyword));
        $this->assign('ad', $data['data']);
        $this->assign('page', $data['page']);
        $this->assign('keyword', input('keyword'));
        return $this->fetch();
    }

    public function add()
    {
        if(Request::instance()->isPost())
        {
            $validate = Loader::validate('Ad');
            $ad = input('post.');
            if($validate->check($ad))
            {
                $adModel = new \app\admin\model\Ad();
                $data = $adModel->upload($ad);
                $ad = array_merge($ad,$data);
                unset($ad['ad_size']);
//                p($ad);die;
                $res = Db::name('ad')->insert($ad);
                if($res)
                {
                    $this->success('添加成功', url('lst'));
                }
                else
                {
                    $this->success('添加失败');
                }
            }
            else
            {
                $this->error($validate->getError());
            }
        }
        $adPositionModel = model('AdPosition');
        $adPosition = $adPositionModel->select();
        $this->assign('adPosition',$adPosition);
        return $this->fetch();
    }

    public function save($id)
    {
        if(Request::instance()->isPost())
        {
            $validate = Loader::validate('Ad');
            $ad = input('post.');
            if($validate->check($ad))
            {
                $adModel = new \app\admin\model\Ad();
                $data = $adModel->upload($ad);
                $ad = array_merge($ad,$data);
                unset($ad['ad_size']);
                unset($ad['old_ad_img']);
//                p( $ad);die;
                $res = Db::name('ad')->update($ad);
                if($res)
                {
                    $this->success('编辑成功', url('lst'));
                }
                else
                {
                    $this->success('编辑失败');
                }
            }
            else
            {
                $this->error($validate->getError());
            }
        }
        // 取出要修改的记录
        $ad = model('Ad');
        $data = $ad->find($id);
        $this->assign('data', $data);

        $adPositionModel = model('AdPosition');
        $adPosition = $adPositionModel->select();
        $this->assign('adPosition',$adPosition);

        //计算出图片大小
        $sql = "SELECT b.adpos_width,b.adpos_height from ".config('database.prefix')."ad  as a LEFT JOIN ".config('database.prefix')."ad_position as b on a.adpos_id = b.id WHERE a.id = $id";
        $size = Db::query($sql);
        $this->assign('size',implode(',',$size[0]));
        return $this->fetch();
    }

    /**
     * 删除
     * @param $id
     */
    public function delete($id)
    {
        //先找出图片删除
        $adModel = db('Ad');
        $ad = $adModel->find($id);
        foreach ($ad as $k=>$v)
        {
            $v = ROOT_PATH.'public'.$v;
            if(file_exists($v))
            {
                unlink($v);
            }
        }
        $adModel->delete($id);
        $this->success('删除成功');
    }


    /**
     * 上传单张图片
     */
    public function ajaxUpload()
    {
        $file = request()->file('img');
        $imgSavePath = ROOT_PATH . 'public/assets/upload/tmp';
        $rules = ['size'=>1024*1024*3,'type'=>'image/png,image/jpeg,image/pjpeg,image/x-png,image/gif']; //上传图片的规则
        $info = $file->validate($rules)->move($imgSavePath);
        if($info)
        {
            $fileName = $info->getFilename();
            $image = Image::open($imgSavePath.'/'.date('Ymd').'/'.$fileName);
            $image->thumb(100, 100)->save($imgSavePath.'/'.date('Ymd').'/thumb_'.$fileName);
            $url = '/assets/upload/tmp/'.date('Ymd').'/'.$fileName;
            $thumb_url = '/assets/upload/tmp/'.date('Ymd').'/thumb_'.$fileName;
            // 在子窗口中的执行JS把数据放到父窗口的表单中
            $js = '<script>';
            $js .=<<<JS
		parent.document.getElementById("logo").value='$url';
		parent.document.getElementById("pre_img").src='$thumb_url';
		parent.document.getElementById("upload").style.display="none";
		parent.document.getElementById("test_pre_img").innerHTML= '';
		parent.document.getElementById("pre_form").reset();
JS;
            $js .= '</script>';
            echo $js;
        }
        else
        {
            // 在子窗口中的执行JS把数据放到父窗口的表单中
            $js = '<script>';
            $js .=<<<JS
		parent.document.getElementById("test_pre_img").innerHTML= '{$file->getError()}';
JS;
            $js .= '</script>';
            echo $js;
        }
    }
}